// ajax封装 wx.request
let system = wx.getSystemInfoSync();
// console.log('system:', system)
// 手机信息 // 调试bug 微信版本 os 小程序
const clientInfo = {
  'clientType': 'mp',
  'appnm': '1711A-pay', // name
  'model': system.model, // 
  'os': system.system,  // 系统
  'screen': system.screenWidth + '*' + system.screenHeight, // 屏幕信息
  'version': App.version || '1.0.1', // 版本
  'channel': '1711A-mp' // 
}
// console.log('clientInfo:', clientInfo)
const errMsg = '服务异常，请稍后重试';
module.exports = {
  // url 参数 loading
  fetch: (url, data = {}, option = {}) => {

    let { loading = true, toast = true, isMock = false, method = 'get' } = option;
    return new Promise((resolve, reject) => {
      if (loading) {
        wx.showLoading({
          title: '加载中...',
          mask: true
        })
      }

      let env = isMock ? App.config.mockApi : App.config.baseApi
      // env: http:localhost:3000
      // baseURL: http:localhost:3000/api/detail
      wx.request({
        url: env + url,
        data,
        method,
        header: {
          'clientInfo': JSON.stringify(clientInfo)
        },
        success: function (result) {
          let res = result.data;// {code:0,data:'',message:''}
          if (res.code == 0) {
            if (loading) {
              wx.hideLoading();
            }
            resolve(res.data);
          } else {
            if (toast) {
              wx.showToast({
                mask: true,
                title: res.messsage,
                icon: 'none'
              })
            } else {
              wx.hideLoading();
            }
            reject(res);
          }
        },
        fail: function (e = { code: -1, msg: errMsg, errMsg }) {
          let msg = e.errMsg;
          if (msg == 'request:fail timeout') {
            msg = '服务请求超时，请稍后处理';
          }
          wx.showToast({
            title: msg,
            icon: 'none'
          })
          reject(e);
        }
      })
    })
  }
}

